<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { type ECharts, init } from 'echarts'
import type { Hot } from '@/types/eCommerce'
import type { Legend, Series, Title } from '@/types/components-echarts'

const props = defineProps<{
  hotData: Hot[]
}>()

const echarts_ref = ref<HTMLDivElement>()
let myEcharts: ECharts


const initEcharts = () => {
  myEcharts = init(echarts_ref.value as HTMLDivElement)
  const initData = {
    grid: {
      top: '15%',
      bottom: '5%',
      containLabel: true
    },
    series: {
      type: 'pie'
    }
  }
  myEcharts.setOption(initData, true)
}

const dataEcharts = (index: number = 0) => {
  const legend: Legend[] = []
  const series: Series[] = []
  if (hotTitle.value.length === 0) {
    const title: Title[] = []
    props.hotData.forEach(item => {
      title.push({
        label: item.name,
        value: item.name
      })
    })
    hotTitle.value = title
    value.value = props.hotData[0].name
  }

  props.hotData[index].children.forEach(item => {
    legend.push({
      name: item.name
    })
    series.push(item)
  })
  const dataOption = {
    legend: {
      data: legend
    },
    series: [{
      data: series
    }]
  }
  myEcharts.setOption(dataOption)
}

const adapterEcharts = () => {
  const width = echarts_ref.value!.offsetWidth
  const adapterOption = {
    series: [{
      barWidth: width / 100 * 5
    }]
  }
  myEcharts.setOption(adapterOption)
  myEcharts.resize()
}

const hotTitle = ref<Title[]>([])
const value = ref()
const hotChange = (value: any) => {
  hotTitle.value.forEach((item, index) => {
    if (value[0] === item.value) {
      dataEcharts(index)
      return
    }
  })
}

const loading = ref(true)
watch(props, () => {
  dataEcharts()
  setTimeout(() => {
    loading.value = false
  }, 300)
})

onMounted(() => {
  initEcharts()
  adapterEcharts()
  window.addEventListener('resize', adapterEcharts)
})

onUnmounted(() => {
  window.removeEventListener('resize', adapterEcharts)
})
</script>

<template>
  <div class="echarts" v-loading="loading">
    <div class="Button">
      <el-cascader v-model="value" :options="hotTitle" @change="hotChange" class="a" style="background-color: #181818"
                   popper-class="dropDownPanel" />
    </div>
    <div ref="echarts_ref" class="echartsDom"></div>
  </div>
</template>

<style lang="css" scoped>
@import "@/assets/style/componentsEcharts.css";
</style>